<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class SemiFinishProduct extends BaseModel
{
    use HasFactory;
    //半成品库
    protected $table = 'semi_finish_product';
    // 允许批量操作的字段
    protected $fillable = ['order_id','finish_time','created_at','updated_at'];

    public function scopeSearch($query,$params)
    {


        //客户
        if(!empty($params['customer_id'])){
            $order_ids = Order::where('customer_id',$params['customer_id'])->pluck('id')->toArray();
            $query->whereIn('order_id',$order_ids);
        }
        //产品
        if(!empty($params['product_id'])){
            $order_ids = Order::where('product_id',$params['product_id'])->pluck('id')->toArray();
            $query->whereIn('order_id',$order_ids);
        }
        //订单号
        if(!empty($params['order_number'])){
            $order_ids = Order::where('order_number',$params['order_number'])->pluck('id')->toArray();
            $query->whereIn('order_id',$order_ids);
        }
        //型号
        if(!empty($params['model_number_id'])){
            $order_ids = Order::where('model_number_id',$params['model_number_id'])->pluck('id')->toArray();
            $query->whereIn('order_id',$order_ids);
        }

        if(!empty($params['start_time']) && !empty($params['end_time'])){
            $query->whereBetween('finish_time',[$params['start_time'],$params['end_time']]);
        }
        $query->where('is_del',2);
        return $query;
    }

    public function order(){
        return $this->hasOne(Order::class,'id','order_id')
            ->with(['color','product_name'=>function($q){
                return $q->select('id','product_name');
            },'customer'=>function($q){
                return $q->select('id','customer_name');
            },'model_number_name','specification'])
            ->select('id','direction','color_id','product_id','customer_id','model_number_id','specification_id',
                'remark','emergency_procedure','batch_number','order_date','order_number','is_stock_up');
    }
}
